package com.example.demogateway.services;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
public class SecurityUserDetailsService implements ReactiveUserDetailsService {

    @Value("${spring.security.user.name}")
    private   String userName;

    @Value("${spring.security.user.password}")
    private   String password;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public Mono<UserDetails> findByUsername(String username) {
        //todo 预留调用数据库根据用户名获取用户
        if(StringUtils.equals(userName,username)){
            List<String> authorityList = new ArrayList<String>();
            authorityList.add("resouce:list");

            List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
            for(String a : authorityList){
                list.addAll(AuthorityUtils.commaSeparatedStringToAuthorityList(a));
            }
            UserDetails user = User.withUsername(userName)
                    //.password(MD5Encoder.encode(password,username))
                    .password(passwordEncoder.encode(password))
                    .roles("admin").authorities(list)
                    .build();
            return Mono.just(user);
        }
        else if(StringUtils.equals("test",username)){
            return Mono.error(new UsernameNotFoundException("状态错误"));
        }
        else{
            return Mono.error(new UsernameNotFoundException("用户名错误"));

        }

    }



}

